<template>
  <div class="tab_content">
    <!-- 统计卡片 -->
    <div class="collect_stats_cards flex" style="margin-bottom: 28px;">
      <div class="stat_card common_block_div flex_ac" :class="{ active: collectFilterType === 'all' }"
        @click="handleStatClick('all')">
        <img :src="getStatIcon(1)" class="stat_icon" alt="" />
        <div class="flex1">
          <div class="stat_label">总项目数</div>
          <div class="stat_value">{{ collectData.all_num }}</div>
        </div>
      </div>
      <div class="stat_card common_block_div flex_ac" style="background: #F0F3FF;"
        :class="{ active: collectFilterType === 'pending' }" @click="handleStatClick('pending')">
        <img :src="getStatIcon(2)" class="stat_icon" alt="" />
        <div class="flex1">
          <div class="stat_label">待审核</div>
          <div class="stat_value">{{ collectData.dsh_num }}</div>
        </div>
      </div>
      <div class="stat_card common_block_div flex_ac" :class="{ active: collectFilterType === 'failed' }"
        @click="handleStatClick('failed')">
        <img :src="getStatIcon(3)" class="stat_icon" alt="" />
        <div class="flex1">
          <div class="stat_label">审核失败</div>
          <div class="stat_value">{{ collectData.shsb_num }}</div>
        </div>
      </div>
      <div class="stat_card common_block_div flex_ac" style="background: #F0F3FF;"
        :class="{ active: collectFilterType === 'scoring' }" @click="handleStatClick('scoring')">
        <img :src="getStatIcon(4)" class="stat_icon" alt="" />
        <div class="flex1">
          <div class="stat_label">评分进行中</div>
          <div class="stat_value">{{ collectData.shcg_num }}</div>
        </div>
      </div>
      <div class="stat_card common_block_div flex_ac" style="background: #F0F3FF;"
        :class="{ active: collectFilterType === 'scored' }" @click="handleStatClick('scored')">
        <img :src="getStatIcon(5)" class="stat_icon" alt="" />
        <div class="flex1">
          <div class="stat_label">已完成评分</div>
          <div class="stat_value">{{ collectData.ypf_num }}</div>
        </div>
      </div>
      <div class="stat_card common_block_div flex_ac" :class="{ active: collectFilterType === 'completed' }"
        @click="handleStatClick('completed')">
        <img :src="getStatIcon(6)" class="stat_icon" alt="" />
        <div class="flex1">
          <div class="stat_label">完结项目</div>
          <div class="stat_value">{{ collectData.yrk_num }}</div>
        </div>
      </div>
    </div>

    <!-- 当前选中提示 -->
    <div class="current_selected">
      <div class="current_selected_left">
        <span class="dark">当前选中:</span>
        <span style="color: #325FFF;">{{ currentSelectedLabel }}</span>
        <span style="margin-left: 12px;">{{ collectListTotal }}条数据</span>
      </div>
      <div class="batch_actions">
        <el-button size="mini" @click="handleBatchAuditSuccess" :disabled="selectedRows.length === 0">批量审核通过</el-button>
        <el-button size="mini" @click="handleBatchAuditFail" :disabled="selectedRows.length === 0">批量审核拒绝</el-button>
      </div>
    </div>

    <!-- 筛选表单 -->
    <div>
      <el-form :model="collectQueryParams" ref="collectQueryForm">
        <el-row :gutter="10">
          <el-col :span="5">
            <FormItem label="项目标题" type="input" :form="collectQueryParams" prop="keywords" placeholder="请输入项目标题"
              clearable @keyenter="handleCollectQuery" />
          </el-col>
          <el-col :span="5">
            <FormItem label="主办单位" type="input" :form="collectQueryParams" prop="company_search" placeholder="请输入主办单位"
              clearable @keyenter="handleCollectQuery" />
          </el-col>
          <el-col :span="5">
            <FormItem label="分数段" type="select" :form="collectQueryParams" prop="score_type"
              :seleDatas="scoreTypeOptions" seleKey="socre_id" seleName="title" clearable />
          </el-col>
          <el-col :span="5">
            <FormItem label="状态" type="select" :form="collectQueryParams" prop="status" :seleDatas="statusOptions"
              seleKey="value" seleName="label" clearable />
          </el-col>
          <el-col :span="4">
            <div class="common_button" style="margin-bottom: 0;padding: 0;">
              <div class="right_button flex_ac">
                <a href="javascript:;" class="color_blue" style="height: 28px;margin-top: 3px;margin-bottom: 6px;"
                  @click="handleCollectQuery">查询</a>
              </div>
              <div class="right_button flex_ac">
                <a href="javascript:;" class="color_dark" style="height: 28px;" @click="resetCollectQuery">重置</a>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div>
      <el-table v-loading="collectLoading" :data="collectList" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="集合编号" align="center" prop="id" width="120" />
        <el-table-column label="赛事名称" align="center" min-width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span
              style="color: #325FFF; cursor: pointer;"
              @click="handleCollectView(scope.row)"
              :title="scope.row.col_title">
              {{ scope.row.col_title || '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="赛事分类" align="center" prop="category_txt" min-width="180"
          :show-overflow-tooltip="true" />
        <el-table-column label="提交单位" align="center" prop="submit_company_title" min-width="200"
          :show-overflow-tooltip="true" />
        <el-table-column label="主办单位" align="center" prop="ho_company_title" min-width="200"
          :show-overflow-tooltip="true" />
        <el-table-column label="基础得分" align="center" prop="base_score" sortable width="100">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.score_text_color }">
              {{ scope.row.base_score || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="评委得分" align="center" prop="pw_score" sortable width="100">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.score_text_color }">
              {{ scope.row.pw_score || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="最终得分" align="center" prop="all_score" sortable width="100">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.score_text_color }">
              {{ scope.row.all_score || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="update_time" width="180" />
        <el-table-column label="审核情况" align="center" prop="status_text" width="120">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.status_text_color }">
              {{ scope.row.status_text }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleCollectView(scope.row)">查看</el-button>
            <!-- <el-button v-if="scope.row.status === 2" type="text" style="color: #325FFF;" @click="handleCollectAudit(scope.row)">审核通过</el-button> -->
            <!-- <el-button v-if="scope.row.status === 2" type="text" style="color: #F56C6C;" @click="handleCollectAudit(scope.row)">审核拒绝</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="collectListTotal > 0" :total="collectListTotal" :page.sync="collectQueryParams.page"
        :limit.sync="collectQueryParams.limit" @pagination="getCollectList" />
    </div>
  </div>
</template>

<script>
import FormItem from "@/components/FormItem/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import collectionApi from "@/api/collection";

export default {
  name: 'CollectProject',
  components: {
    FormItem,
    Pagination
  },
  props: {
    projectId: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    http: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      collectStats: [
        { type: 'all', label: '总项目数', value: 238, icon: 'el-icon-menu', color: '#67C23A' },
        { type: 'pending', label: '待审核', value: 238, icon: 'el-icon-user', color: '#409EFF' },
        { type: 'failed', label: '审核失败', value: 0, icon: 'el-icon-close', color: '#F56C6C' },
        { type: 'scoring', label: '评分进行中', value: 0, icon: 'el-icon-time', color: '#409EFF' },
        { type: 'scored', label: '已完成评分', value: 0, icon: 'el-icon-success', color: '#67C23A' },
        { type: 'completed', label: '完结项目', value: 0, icon: 'el-icon-check', color: '#409EFF' }
      ],
      collectFilterType: 'pending',
      collectLoading: false,
      collectList: [],
      collectData: {
        all_num: 0,
        dsh_num: 0,
        shsb_num: 0,
        shcg_num: 0,
        ypf_num: 0,
        yrk_num: 0
      },
      collectListTotal: 0,
      selectedRows: [], // 选中的行数据
      collectQueryParams: {
        page: 1,
        limit: 16,
        keywords: '',
        company_search: '',
        score_type: '',
        status: ''
      },
      filterTypeOptions: [
        { value: '', label: '全部' }
      ],
      contentTypeOptions: [
        { value: '', label: '全部' }
      ],
      statusOptions: [],
      scoreTypeOptions: []
    }
  },
  computed: {
    currentSelectedLabel() {
      const stat = this.collectStats.find(s => s.type === this.collectFilterType);
      return stat ? stat.label : '全部';
    }
  },
  methods: {
    handleStatClick(type) {
      this.collectFilterType = type;
      // this.collectQueryParams.status = type === 'all' ? '' : type;
      // this.collectQueryParams.page = 1;
      // this.getCollectList();
    },
    getCollectList() {
      const _this = this;
      if (!this.projectId) {
        this.collectList = [];
        this.collectListTotal = 0;
        return;
      }

      this.collectLoading = true;
      const params = {
        ...this.collectQueryParams,
        project_id: this.projectId
      };

      // 如果选择了筛选类型，添加到参数中
      // if (this.collectFilterType && this.collectFilterType !== 'all') {
      //   params.status = this.collectFilterType;
      // }

      // 使用 collection.js 中的 list 接口
      collectionApi.list(params).then(function (res) {
        if (res && res.message) {
          _this.collectList = res.message.data || [];
          _this.collectData = res.message.top_data || {};
          _this.collectListTotal = res.message.total || 0;
        } else {
          _this.collectList = [];
          _this.collectListTotal = 0;
        }
        _this.collectLoading = false;
      }).catch(function (error) {
        console.error('获取采集列表失败:', error);
        _this.$message.error('获取采集列表失败');
        _this.collectList = [];
        _this.collectListTotal = 0;
        _this.collectLoading = false;
      });
    },
    handleCollectQuery() {
      this.collectQueryParams.page = 1;
      this.getCollectList();
    },
    resetCollectQuery() {
      this.collectQueryParams = {
        page: 1,
        limit: 16,
        keywords: '',
        company_search: '',
        score_type: '',
        status: ''
      };
      this.collectFilterType = 'all';
      this.handleCollectQuery();
    },
    handleDownloadForm() {
      if (!this.projectId) {
        this.$message.warning('请先保存项目');
        return;
      }
      const url = this.http + '/manage/template/downloadForm?id=' + this.projectId;
      window.open(url);
    },
    handleCollectView(row) {
      // 查看详情
      this.$router.push({
        path: '/project/review',
        query: {
          id: row.id,
          title: this.title
        }
      });
    },
    handleCollectAudit(row) {
      // 审核
      this.$message.info('审核功能待开发');
    },
    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    // 批量审核通过
    handleBatchAuditSuccess() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要审核的项目');
        return;
      }
      const ids = this.selectedRows.map(row => row.id);
      this.$confirm(`确定要批量审核通过 ${ids.length} 个项目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        collectionApi.batchAuditSuccess({ ids }).then((res) => {
          if (res) {
            this.$message.success('批量审核通过成功');
            this.selectedRows = [];
            this.getCollectList();
          } else {
            this.$message.error(res.message || '批量审核通过失败');
          }
        }).catch((error) => {
          console.error('批量审核通过失败:', error);
          this.$message.error('批量审核通过失败');
        });
      }).catch(() => { });
    },
    // 批量审核拒绝
    handleBatchAuditFail() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要审核的项目');
        return;
      }
      const ids = this.selectedRows.map(row => row.id);
      this.$prompt('请输入审核不通过的原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入失败原因',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请输入失败原因';
          }
          return true;
        }
      }).then(({ value }) => {
        collectionApi.batchAuditFail({
          ids,
          reason: value.trim()
        }).then((res) => {
          if (res) {
            this.$message.success('批量审核拒绝成功');
            this.selectedRows = [];
            this.getCollectList();
          } else {
            this.$message.error(res.message || '批量审核拒绝失败');
          }
        }).catch((error) => {
          console.error('批量审核拒绝失败:', error);
          this.$message.error('批量审核拒绝失败');
        });
      }).catch(() => { });
    },
    getAuditStatusText(status) {
      const statusMap = {
        'pending': '待审核',
        'completed': '审核完成',
        'failed': '审核失败'
      };
      return statusMap[status] || '未知';
    },
    getAuditStatusColor(status) {
      const colorMap = {
        'pending': '#E6A23C',
        'completed': '#67C23A',
        'failed': '#F56C6C'
      };
      return colorMap[status] || '#909399';
    },
    getStatIcon(index) {
      const iconMap = {
        1: require('@/assets/project_icon_1.png'),
        2: require('@/assets/project_icon_2.png'),
        3: require('@/assets/project_icon_3.png'),
        4: require('@/assets/project_icon_4.png'),
        5: require('@/assets/project_icon_5.png'),
        6: require('@/assets/project_icon_6.png'),
        7: require('@/assets/project_icon_7.png')
      };
      return iconMap[index] || iconMap[1];
    },
    // 获取状态下拉数据
    getStatusOptions() {
      const _this = this;

      // 调用状态数据接口获取下拉选项
      collectionApi.statusData().then(function (res) {
        if (res && res.message) {
          const data = res.message;
          // 更新状态下拉选项
          _this.statusOptions = data || [];
        }
      }).catch(function (error) {
        console.error('获取状态下拉数据失败:', error);
      });
    },
    // 获取分数段下拉数据
    getScoreTypeOptions() {
      const _this = this;

      // 调用分数段数据接口获取下拉选项
      collectionApi.scoreType().then(function (res) {
        if (res && res.message) {
          const data = res.message;
          // 更新分数段下拉选项
          _this.scoreTypeOptions = data || [];
        }
      }).catch(function (error) {
        console.error('获取分数段下拉数据失败:', error);
      });
    }
  },
  mounted() {
    this.getCollectList();
    this.getStatusOptions();
    this.getScoreTypeOptions();
  }
}
</script>

<style lang="scss" scoped>
.tab_content {
  padding: 20px 0;
  min-height: 300px;
}

.collect_stats_cards {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.stat_card {
  box-sizing: border-box;
  flex: 0 0 calc(25% - 15px);
  height: 80px;
  padding: 17px 19px;
  background: #EAF8F8;
  border: 1px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.stat_card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat_card.active {
  border-color: #409EFF;
  background: #ECF5FF;
}

.stat_value {
  font-family: DIN, DIN;
  font-weight: 700;
  font-size: 24px;
  color: #1D2129;
  line-height: 22px;
}

.stat_label {
  font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
  font-weight: 400;
  font-size: 14px;
  color: #1D2129;
  line-height: 22px;
}

.stat_icon {
  width: 46px;
  height: 46px;
  object-fit: contain;
  flex-shrink: 0;
  margin-right: 16px;
}

.current_selected {
  margin-bottom: 25px;
  padding: 0 18px;
  height: 50px;
  font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
  font-weight: 400;
  font-size: 16px;
  color: #86909C;
  line-height: 50px;
  background: #F2F3F5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.current_selected_left {
  display: flex;
  align-items: center;
}

.current_selected .dark {
  margin-right: 5px;
  font-family: PingFang SC, PingFang SC;
  color: #1D2129;
}

.search_btns .el-button {
  margin-right: 10px;
}

.batch_actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch_actions .el-button {
  margin-right: 0;
}

.selected_count {
  margin-left: 12px;
  font-size: 14px;
  color: #606266;
}

::v-deep .el-form-item--small {
  margin-bottom: 0 !important;
}
</style>
